# -*- coding: <encoding name> -*-
"""
========================================================================================================================
@Author：mengying
@file： myProcessLog.py
@date：2023/6/14 17:11
@email: 652044581@qq.com
@desc: 中间件记录过程日志
========================================================================================================================
"""
from utils.myLog import SimpleLog
from sanic.response.types import JSONResponse
import time


class ProcessLog(object):
    """
    @param: request 请求对象
    @param: response 相应对象
    @param: exception 异常对象
    @desc: 请求返回过程中的日志和耗时
    """

    def __init__(self, request, response=None):
        self.request = request
        self.response = response

    def action(self):
        if not self.response:
            self.request.headers['my-duration'] = time.time()
            if self.request.method == "POST":
                if self.request.content_type == 'application/json':
                    self.records(self.request.id.hex, self.request.path, self.request.method, self.request.json)
                else:
                    self.records(self.request.id.hex, self.request.path, self.request.method, self.request.form)
            else:
                self.records(self.request.id.hex, self.request.path, self.request.method, self.request.args)
        else:
            if isinstance(self.response, JSONResponse):
                duration = time.time() - self.request.headers['my-duration']
                self.response.headers['my-log'] = self.request.id.hex
                self.response.headers['my-duration'] = duration
                self.records(self.request.id.hex, self.request.path, self.request.method, self.response.raw_body,
                             duration)

    @classmethod
    def records(cls, uid, path, method, data, duration=None):
        request_info = {'链路id:': uid, "接口:": path, "请求类型:": method, '数据:': data}
        if duration:
            request_info.update({'接口耗时:': duration})

        SimpleLog.info(str(request_info))
